package com.blog.service.impl;


import com.blog.dto.ArticleCardDTO;
import com.blog.dto.Result;
import com.blog.entity.Article;
import com.blog.entity.Tag;
import com.blog.mapper.ArticleMapper;
import com.blog.mapper.BlogTagMapper;
import com.blog.mapper.CategoryMapper;
import com.blog.service.CategoryService;
import com.blog.service.TagService;
import com.blog.mapper.TagMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.blog.utils.MarkdownUtil.Markdown;

/**
* @author 电脑小白
* @description 针对表【tag】的数据库操作Service实现
* @createDate 2025-07-03 19:35:39
*/
@Service
public class TagServiceImpl implements TagService{
    @Resource
    private TagMapper tagMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private BlogTagMapper blogTagMapper;
    @Override
    public Result get_tag_page_list(Integer tagId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<Article> articles = articleMapper.get_tag_page_list(tagId);
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        List<ArticleCardDTO> articleCardDTOS = articles.stream()
                .map(article -> ArticleCardDTO.builder()
                        .Id(article.getId())          // 设置文章ID
                        .title(article.getTitle())                // 设置标题
                        .mainContent(Markdown(article.getContent()))       // 设置主要内容
                        .createTime(article.getCreateTime().toString()) // 设置创建时间（转字符串）
                        .categoryName(categoryMapper.getcategorybyId(article.getCategoryId())) // 通过分类ID获取分类名称
                        .author(article.getAuthor())              // 设置作者
                        .viewCount(article.getViewCount())        // 设置浏览量
                        .tags(blogTagMapper.get_tag(article.getId()))
                        .total((int) pageInfo.getTotal())
                        .status(2)
                        .build()                                  // 构建 ArticleCardDTO 对象
                )
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", articleCardDTOS); // DTO 列表
        result.put("total", pageInfo.getTotal()); // 总记录数
        result.put("pageNum", pageInfo.getPageNum()); // 当前页
        result.put("pageSize", pageInfo.getPageSize()); // 每页大小
        return Result.ok(result);
    }

    @Override
    public Result get_tag_name(Integer tagId) {
        return Result.ok(tagMapper.gettagbyid(tagId).getTagName());
    }

    @Override
    public Result get_tag() {
        List<Tag> tags = tagMapper.get_tag();
        return Result.ok(tags);
    }
}




